//
//  Utils.m
//  Medical_Wisdom
//
//  Created by Mac on 14-1-26.
//  Copyright (c) 2014年 NanJingXianLang. All rights reserved.
//

#import "Utils.h"
//#import "Pinterface.h"
#import "AppDelegate.h"
#import <CommonCrypto/CommonDigest.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#import "SDImageCache.h"

@implementation Utils

+(NSString *)getMd5_32Bit:(NSString *)dataBase
{
    const char *cStr = [dataBase UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, (CC_LONG)dataBase.length, digest );
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [result appendFormat:@"%02x", digest[i]];
    return result;
}

+(NSMutableArray *)getDictionaries:(NSDictionary *)allKeys
{
    NSEnumerator * enumerator = [allKeys keyEnumerator];
    NSMutableArray *getArray=[NSMutableArray array];
   
    for (int i=0; i<allKeys.count; i++) {
        NSString *resultKey=[enumerator nextObject];
        NSLog(@"%@",resultKey);
        NSString * resultKeyS=[allKeys objectForKey:resultKey];
        NSLog(@"%@",resultKeyS);
        [getArray addObject:resultKeyS];
    }
    return getArray;
}
/*
 AppDelegate
 */
+ (AppDelegate *)applicationDelegate
{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

+ (UIImageView *)imageViewWithFrame:(CGRect)frame withImage:(UIImage *)image{
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
    imageView.image = image;
    return imageView;
}

+ (UILabel *)labelWithFrame:(CGRect)frame withTitle:(NSString *)title titleFontSize:(UIFont *)font textColor:(UIColor *)color backgroundColor:(UIColor *)bgColor alignment:(NSTextAlignment)textAlignment{
    
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.text = title;
    label.font = font;
    label.textColor = color;
    label.backgroundColor = bgColor;
    label.textAlignment = textAlignment;
    return label;
    
}

//alertView
+(UIAlertView *)alertTitle:(NSString *)title message:(NSString *)msg delegate:(id)aDeleagte cancelBtn:(NSString *)cancelName otherBtnName:(NSString *)otherbuttonName{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:aDeleagte cancelButtonTitle:cancelName otherButtonTitles:otherbuttonName, nil];
    [alert show];
    return alert;
}

+(UIButton *)createBtnWithType:(UIButtonType)btnType frame:(CGRect)btnFrame backgroundColor:(UIColor*)bgColor{
    UIButton *btn = [UIButton buttonWithType:btnType];
    btn.frame = btnFrame;
    [btn setBackgroundColor:bgColor];
    return btn;
}

//利用正则表达式验证邮箱的合法性
+(BOOL)isValidateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
    
}
+(BOOL)isUserName:(NSString *)userName
{
    NSString *      regex = @"(^[A-Za-z0-9]{3,20}$)";
    NSPredicate *   pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    return [pred evaluateWithObject:userName];
}

+(BOOL)isPassword:(NSString *)password
{
    NSString *      regex = @"(^[A-Za-z0-9]{4,10}$)";
    NSPredicate *   pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    return [pred evaluateWithObject:password];
}

+(BOOL)isQQ:(NSString *)password
{
    NSString *      regex = @"(^[0-9]{6,12}$)";
    NSPredicate *   pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    return [pred evaluateWithObject:password];
}
+(BOOL)isNumber:(NSString *)password
{
    NSString *      regex = @"(^[0-9]{1,50000}$)";
    NSPredicate *   pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    return [pred evaluateWithObject:password];
}
+(BOOL)isUID:(NSString *)password
{
    BOOL flag;
    if (password.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *      regex = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *   pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    return [pred evaluateWithObject:password];
}

+(BOOL)isID:(NSString *)idNum{
    BOOL flag;
    if (idNum.length != 15 && idNum.length != 18) {
        flag = NO;
        return flag;
    }
    NSString * regex = @"^(\\d{15}|\\d{18}|\\d{17}(\\d|X|x))$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pred evaluateWithObject:idNum];
}

+(BOOL)isUrl:(NSString *)urls
{
    NSString *      regex = @"http(s)?:\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&=]*)?";
    NSPredicate *   pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    return [pred evaluateWithObject:urls];
}

+(BOOL)isTelephone:(NSString *)mobile
{
    if (mobile.length != 11)
    {
        return NO;
    }
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9]
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     * 联通号段: 130,131,132,155,156,185,186,145,176,1709
     * 电信号段: 133,153,180,181,189,177,1700
     */
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$";
    /**
     * 中国移动：China Mobile
     * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     */
    NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
    /**
     * 中国联通：China Unicom
     * 130,131,132,155,156,185,186,145,176,1709
     */
    NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)";
    /**
     * 中国电信：China Telecom
     * 133,153,180,181,189,177,1700
     */
    NSString *CT = @"(^1(33|53|77|8[019])\\d{8}$)|(^1700\\d{7}$)";
    NSString *myNum = @"(^1[34578]\\d{9}$)";
    //17502853446
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    NSPredicate *regestMynum = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",myNum];
    if (([regextestmobile evaluateWithObject:mobile] == YES)
        || ([regextestcm evaluateWithObject:mobile] == YES)
        || ([regextestct evaluateWithObject:mobile] == YES)
        || ([regextestcu evaluateWithObject:mobile] == YES) || ([regestMynum evaluateWithObject:mobile] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
+(BOOL)isChinese:(NSString *)china
{
    NSString *regex=@"[\u4e00-\u9fa5]{1,500}";
    NSPredicate *   pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:china];
}
//昵称
+ (BOOL) validateNickname:(NSString *)nickname
{
    NSString *nicknameRegex = @"^[\u4e00-\u9fa5]{2,8}$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    return [passWordPredicate evaluateWithObject:nickname];
}

//车牌号验证
+ (BOOL) validateCarNo:(NSString *)carNo
{
    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    NSLog(@"carTest is %@",carTest);
    return [carTest evaluateWithObject:carNo];
}


//车型
+ (BOOL) validateCarType:(NSString *)CarType
{
    NSString *CarTypeRegex = @"^[\u4E00-\u9FFF]+$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CarTypeRegex];
    return [carTest evaluateWithObject:CarType];
}
//  十进制转二进制
#pragma marke--十进制转二进制
+(NSString *)toBinarySystemWithDecimalSystem:(NSString *)decimal

{
    
    int num = [decimal intValue];
    
    int remainder = 0;      //余数
    
    int divisor = 0;        //除数
    
    
    
    NSString * prepare = @"";
    
    
    
    while (true)
        
    {
        
        remainder = num%2;
        
        divisor = num/2;
        
        num = divisor;
        
        prepare = [prepare stringByAppendingFormat:@"%d",remainder];
        
        
        
        if (divisor == 0)
            
        {
            
            break;
            
        }
        
    }
    
    
    
    NSString * result = @"";
    for (int i = (int)prepare.length - 1; i >= 0; i --)
        
    {
        
        result = [result stringByAppendingFormat:@"%@",
                  
                  [prepare substringWithRange:NSMakeRange(i , 1)]];
        
    }
    
    
    
    return result;
    
}
#pragma marke--二进制转十进制
+ (NSString *)toDecimalSystemWithBinarySystem:(NSString *)binary

{
    
    int ll = 0 ;
    
    int  temp = 0 ;
    
    for (int i = 0; i < binary.length; i ++)
        
    {
        
        temp = [[binary substringWithRange:NSMakeRange(i, 1)] intValue];
        
        temp = temp * powf(2, binary.length - i - 1);
        
        ll += temp;
        
    }
    
    
    
    NSString * result = [NSString stringWithFormat:@"%d",ll];
    
    
    
    return result;
    
}
//+ (NSString *)cookieValueWithKey:(NSString *)key
//{
//    NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//
//    if ([sharedHTTPCookieStorage cookieAcceptPolicy] != NSHTTPCookieAcceptPolicyAlways) {
//        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
//    }
//
//    NSArray         *cookies = [sharedHTTPCookieStorage cookiesForURL:[NSURL URLWithString:IPaddress]];
//    NSEnumerator    *enumerator = [cookies objectEnumerator];
//    NSHTTPCookie    *cookie;
//    while (cookie = [enumerator nextObject]) {
//        if ([[cookie name] isEqualToString:key]) {
//            return [NSString stringWithString:[[cookie value] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//        }
//    }
//
//    return nil;
//}
///因为cookies保存在NSHTTPCookieStorage.cookies中.这里删除它里边的元素即可.
//+ (void)deleteCookieWithKey:(NSString *)key
//{
//    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//
//    NSArray *cookies = [NSArray arrayWithArray:[cookieJar cookies]];
//
//    for (NSHTTPCookie *cookie in cookies) {
//        if ([[cookie name] isEqualToString:key]) {
//            [cookieJar deleteCookie:cookie];
//        }
//    }
//}
//#pragma marke--解析域名
//+ (NSString *)ipAddressFromDomain:(NSString *)strDomain
//{
//    struct hostent *hostentry = NULL;
//    hostentry = gethostbyname([strDomain cStringUsingEncoding:NSASCIIStringEncoding]);
//    if (hostentry == NULL) {
//        NSLog(@"ERROR: ipAddressFromDomain: - gethostbyname error");
//        return nil;
//    }
//    char * ipbuf = NULL;
//    ipbuf = inet_ntoa(*((struct in_addr *)hostentry->h_addr_list[0]));
//    if (ipbuf == NULL) {
//        NSLog(@"ERROR: ipAddressFromDomain: - inet_ntoa error");
//        return nil;
//    }
//
//    NSString * address = [[NSString alloc] initWithCString:ipbuf encoding:NSASCIIStringEncoding];
//
//    return address;
//}


//判断是否为整形：判断是否为浮点形：


//+ (BOOL)isPureIntOrFloat:(NSString*)string{
//
//    NSScanner* scan = [NSScanner scannerWithString:string];
//
//    int val;
//    float valf;
//
//    return([scan scanInt:&val] && [scan isAtEnd])||([scan scanFloat:&valf] && [scan isAtEnd]);
//
//}
//清理缓存文件
+(void)removeCache
{
    //===============清除缓存==============
    NSString *cachePath =[ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    //    NSLog(@"文件数 ：%d",[files count]);
    for (NSString *p in files)
    {
        NSError *error;
        NSString *path = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",p]];
        if([[NSFileManager defaultManager] fileExistsAtPath:path])
        {
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }
}
// 显示缓存大小
+( float )filePath

{
    
    
    //获取当前沙盒路劲
    NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
    
    
    
    return [self folderSizeAtPath :cachPath];
    
    
    
}
//遍历文件夹获得文件夹大小，返回多少 M（提示：你可以在工程界设置（)m）
+( float ) folderSizeAtPath:( NSString *) folderPath{
    
    
    
    NSFileManager * manager = [ NSFileManager defaultManager ];
    
    
    
    if (![manager fileExistsAtPath :folderPath]) return 0 ;
    
    
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator ];
    
    
    
    NSString * fileName;
    
    
    
    long long folderSize = 0 ;
    
    
    
    while ((fileName = [childFilesEnumerator nextObject ]) != nil ){
        
        
        
        NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent :fileName];
        
        
        
        folderSize += [ self fileSizeAtPath :fileAbsolutePath];
        
        
        
    }
    
    
    
    return folderSize/( 1024.0 * 1024.0 );
    
    
    
}
//首先我们计算一下 单个文件的大小
+( long long )fileSizeAtPath:( NSString *) filePath{
    
    
    
    NSFileManager * manager = [ NSFileManager defaultManager ];
    
    
    
    if ([manager fileExistsAtPath :filePath]){
        
        
        
        return [[manager attributesOfItemAtPath :filePath error : nil ] fileSize ];
        
    }
    
    
    
    return 0 ;
    
    
    
}
/**
 *  SDWebImage  删除特定url图片的缓存
 */
+ (void)clearCacheWithUrl:(NSString *)url
{
    
    [[SDImageCache sharedImageCache]removeImageForKey:url withCompletion:nil];
}
//#pragma  mark 自定义提示框
//+(void)tipsPromptBox:(NSString *)NameText viewC:(UIView *)views hightNum:(int)number
//{
//
//    UIView *view=[[UIView alloc]init];
//    view.alpha=0.3;
//    CALayer *layer = [view layer];
//    [layer setMasksToBounds:YES];
//    [layer setCornerRadius:5.0];
//    [layer setBorderWidth:0.01];
//    view.backgroundColor=CGUIColor(0, 0, 0);
//    UILabel *_nameLabel=[[UILabel alloc]init];
//    _nameLabel.textColor=[UIColor whiteColor];
//    _nameLabel.text=NameText;
//    _nameLabel.numberOfLines = 0;
//    // 设置Label的字体 HelveticaNeue  Courier
//    UIFont *fnt = [UIFont fontWithName:@"PingFangSC-Regular" size:20.0f];
//    _nameLabel.font = fnt;
//    // 根据字体得到NSString的尺寸
//    CGFloat contentW = views.bounds.size.width;
//    CGFloat contentH = views.bounds.size.height;
//    //     CGRect tmpRect = [_nameLabel.text boundingRectWithSize:CGSizeMake(100, 100) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil] context:nil];
//    NSDictionary *attributes = @{NSFontAttributeName:fnt,};
//
//
//    CGSize tmpRect = [_nameLabel.text boundingRectWithSize:CGSizeMake(contentW, contentW) options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
//    // 名字的H
//    CGFloat nameH =tmpRect.height;
//    // 名字的W
//    CGFloat nameW = tmpRect.width;
//    _nameLabel.frame = CGRectMake(10, 5, nameW,nameH);
//    [view addSubview:_nameLabel];
//    view.frame=CGRectMake((contentW-nameW)/2, contentH/number, nameW+20,nameH+20);
//    [views addSubview:view];
//    _nameLabel.frame = CGRectMake(10, CGRectGetHeight(view.frame)/4 , nameW,nameH);
//    [UIView animateWithDuration:4.0 // 动画时长
//                          delay:0.0 // 动画延迟
//         usingSpringWithDamping:1.0 // 类似弹簧振动效果 0~1
//          initialSpringVelocity:2.0 // 初始速度
//                        options:UIViewAnimationOptionCurveEaseInOut // 动画过渡效果
//                     animations:^{
//                         // code...
//                         CGPoint point = view.center;
//                         point.y += 50;
//                         [view setCenter:point];
//                     } completion:^(BOOL finished) {
//                         // 动画完成后执行
//                         // code...
//                         [UIView animateWithDuration:1.0 animations:^{
//                             view.alpha=0.1;
//                         } completion:^(BOOL finished) {
//                             [view removeFromSuperview];
//                         }];
//
//                     }];
//}

//+(BOOL)checkUserID:(NSString *)userID
//{
//    //长度不为18的都排除掉
//    if (userID.length!=18) {
//        return NO;
//    }
//
//    //校验格式
//    NSString *regex2 = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
//    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
//    BOOL flag = [identityCardPredicate evaluateWithObject:userID];
//
//    if (!flag) {
//        return flag;    //格式错误
//    }else {
//        //格式正确在判断是否合法
//
//        //将前17位加权因子保存在数组里
//        NSArray * idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
//
//        //这是除以11后，可能产生的11位余数、验证码，也保存成数组
//        NSArray * idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
//
//        //用来保存前17位各自乖以加权因子后的总和
//        NSInteger idCardWiSum = 0;
//        for(int i = 0;i < 17;i++)
//        {
//            NSInteger subStrIndex = [[userID substringWithRange:NSMakeRange(i, 1)] integerValue];
//            NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
//
//            idCardWiSum+= subStrIndex * idCardWiIndex;
//
//        }
//
//        //计算出校验码所在数组的位置
//        NSInteger idCardMod=idCardWiSum%11;
//
//        //得到最后一位身份证号码
//        NSString * idCardLast= [userID substringWithRange:NSMakeRange(17, 1)];
//
//        //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
//        if(idCardMod==2)
//        {
//            if([idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"])
//            {
//                return YES;
//            }else
//            {
//                return NO;
//            }
//        }else{
//            //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
//            if([idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]])
//            {
//                return YES;
//            }
//            else
//            {
//                return NO;
//            }
//        }
//    }
//}

@end
